﻿using System.Net;

namespace Mes.Application.Web.Middlewares
{
    public class GlobalExceptionMiddleware
    {
        private readonly RequestDelegate _next;

        public GlobalExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception exception)
            {
                await HandleExceptionAsync(context, exception);
            }
        }

        private async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            context.Response.ContentType = "plain/text";
            context.Response.StatusCode = exception switch
            {
                ApplicationException => (int)HttpStatusCode.BadRequest,
                KeyNotFoundException => (int)HttpStatusCode.NotFound,
                _ => (int)HttpStatusCode.InternalServerError
            };
            var logFac = context.RequestServices.GetRequiredService<ILoggerFactory>();
            var logger=logFac.CreateLogger<GlobalExceptionMiddleware>();
            logger.LogError($"Server internal error: {exception}");
            await context.Response.WriteAsync("applicationerror");
        }
    }
}
